package demo;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;

/**
 * @author 杜志锋
 * @date 2021年04月28日 11:25
 */
public class HttpsLink {
    //调用接口凭证
    public static String token;
    //企业ID
    public static String ID;
    //应用的凭证密钥
    public static String SECRET;

    public static void main(String[] args) throws Exception {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/service/get_corp_token?" +
                "suite_access_token=" + token;
        String request = "POST";
        JsonObject jo = getJsonObject(url, request);
        String s = jo.get("errcode").getAsString();
        if (!"0".equals(s)) {
            //token失效，重新获取
            getToken();
            jo = getJsonObject(url, request);
        }
        System.out.println("errcode" + s);
    }

    /**
     * 获取token
     *
     * @author 杜志锋
     * @date 2021/4/28 11:23
     */
    private static void getToken() throws IOException {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + ID + "&corpsecret=" + SECRET;
        String request = "GET";
        JsonObject jo = getJsonObject(url, request);
        String errcode = jo.get("errcode").getAsString();
        if (!"0".equals(errcode)) {
            System.out.println("token获取失败,失败码 " + errcode);
        }else {
            token = jo.get("access_token").getAsString();
        }
    }


    /**
     * 获取JSON字符串对象
     *
     * @param url
     * @param request
     * @return com.google.gson.JsonObject
     * @author 杜志锋
     * @date 2021/4/28 11:02
     */
    private static JsonObject getJsonObject(String url, String request) throws IOException {
        URL reqURL = new URL(url); //创建URL对象
        HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL.openConnection();

        httpsConn.setDoOutput(true);
        httpsConn.setRequestMethod(request);
        OutputStreamWriter out = new OutputStreamWriter(httpsConn.getOutputStream());
//        out.write("xxxx");
        out.flush();
        out.close();
        //取得该连接的输入流，以读取响应内容 
        InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream());
        //读取服务器的响应内容并显示
        int respInt = insr.read();
        StringBuffer buffer = new StringBuffer();
        while (respInt != -1) {
            buffer = buffer.append((char) respInt);
            respInt = insr.read();
        }
        String str = new String(buffer);
        System.out.println("链接返回的JSON字符串 " + str);
        JsonParser jp = new JsonParser();
        return jp.parse(str).getAsJsonObject();
    }
}
